<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_locale_GTranslate
{
    private $url = "http://ajax.googleapis.com/ajax/services/language/translate";
    private $api_version = "1.0";
    private $fromLang;
    private $toLang;
    private $string;

    /**
     * @param string $string
     */
    private function __construct($string)
    {
        $this->string = urlencode($string);
    }

    /**
     * @param string $string
     * @return f_locale_GTranslate
     */
    public static function getInstance($string)
    {
        return new self($string);
    }

    /**
     * @param string $lang
     * @return f_locale_GTranslate
     */
    public function fromLang($lang)
    {
        $this->fromLang = $lang;
        return $this;
    }

    /**
     * @param string $lang
     * @return f_locale_GTranslate
     */
    public function toLang($lang)
    {
        $this->toLang = $lang;
        return $this;
    }

    /**
     * @return string
     */
    public function translate()
    {
        $response = json_decode(file_get_contents($this->url."?v=".$this->api_version.'&langpair='.$this->fromLang.'|'.$this->toLang.'&q='.$this->string));

        switch($response->responseStatus)
		{
			case 200:
				return $response->responseData->translatedText;
				break;
			default:
				return urldecode($this->string);
			break;
		}
    }
}
